package com.tanhua.server.service;

import com.tanhua.domain.db.Character;
import com.tanhua.domain.db.*;
import com.tanhua.domain.vo.*;
import com.tanhua.dubbo.api.*;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class SoulService {

    @Reference
    private TopicApi topicApi;

    @Reference
    private OptionsApi optionsApi;


    @Reference
    private CharacterApi characterApi;

    @Reference
    private QuestionnaireApi questionnaireApi;

    @Reference
    private UserInfoApi userInfoApi;

    @Autowired
    private  RedisTemplate<String, String> redisTemplate;


    /**
     * 接口名称：测灵魂-问卷列表（学生实战）
     */
    public ResponseEntity<Object> testSoul() {

        // 查询问卷表
        List<Questionnaire> questionnaireList = questionnaireApi.findAll();

        List<SoulVo> soulVoList = new ArrayList<>();

        for (Questionnaire questionnaire : questionnaireList) {

            List<QuestionsVo> questionsVoList = new ArrayList<>();

            List<Topic> topicList = topicApi.findLevel(questionnaire.getId());

            for (Topic topic : topicList) {

                // 根据试题id查询选项
                List<Options> optionsList = optionsApi.findOptionsList(topic.getId());

                // 封装选项数据
                List<OptionsVo> optionsVoList = new ArrayList<>();
                for (Options options : optionsList) {
                    OptionsVo optionsVo = new OptionsVo();
                    optionsVo.setId(options.getId().toString());
                    optionsVo.setOption(options.getOptions());
                    optionsVoList.add(optionsVo);
                }
                // 封装数据到试题
                QuestionsVo questionsVo = new QuestionsVo();
                questionsVo.setId(topic.getId().toString());
                questionsVo.setQuestion(topic.getQuestion());
                questionsVo.setOptions(optionsVoList);
                questionsVoList.add(questionsVo);
            }

            // 封装vo
            SoulVo soulVo = new SoulVo();
            soulVo.setId(questionnaire.getId().toString());
            soulVo.setName(questionnaire.getName());
            soulVo.setCover(questionnaire.getCover());
            soulVo.setLevel(questionnaire.getLevel());
            soulVo.setStar(questionnaire.getStar());
            soulVo.setQuestions(questionsVoList);

            String soulKey="SOUL_"+UserHolder.getUserId()+"_"+questionnaire.getId();

            if (questionnaire.getId()==1 || redisTemplate.hasKey(soulKey) ) {
                soulVo.setIsLock(0);
            }else {
                soulVo.setIsLock(1);
            }
            soulKey="SOUL_"+UserHolder.getUserId()+"_"+(questionnaire.getId()+1);
            if (redisTemplate.hasKey(soulKey)) {
                String soulScoreKey = "SOUL_SCORE_"+UserHolder.getUserId();
                if (redisTemplate.hasKey(soulScoreKey)){
                    soulVo.setReportId(redisTemplate.opsForValue().get(soulScoreKey));
                }else {
                    soulVo.setReportId("5");
                }
            }else {
                soulVo.setReportId(null);
            }
            soulVoList.add(soulVo);
       }
        return ResponseEntity.ok(soulVoList);
    }
    /**
     * 接口名称：测灵魂-提交问卷（学生实战）
     */
    public ResponseEntity<Object> submitSoul(List<Map<String, String>> answers) {

        Long questionnaireId = null;

        Integer score = 0;

        for (Map answer : answers) {
            String questionId = (String) answer.get("questionId");
            String optionId = (String) answer.get("optionId");
            // 调用选项表，查询分数
            score += optionsApi.findByScore(Integer.parseInt(questionId), Integer.parseInt(optionId));

            Topic topic = topicApi.findById(Integer.parseInt(questionId));
            questionnaireId = topic.getQuestionnaireId();
        }

        // 将用户答过的题目放到redis中
        String soulKey="SOUL_"+UserHolder.getUserId()+"_"+(questionnaireId+1);
        redisTemplate.opsForValue().set(soulKey,score.toString());

        UserInfo userInfo = userInfoApi.findById(UserHolder.getUserId());

        // 分析性格
        if (score<21){
            userInfo.setCharacterId(1);
        }else if (score<=40){
            userInfo.setCharacterId(2);
        }else if (score<=55){
            userInfo.setCharacterId(3);
        }else {
            userInfo.setCharacterId(4);
        }
        userInfoApi.update(userInfo);

        String soulScoreKey = "SOUL_SCORE_"+UserHolder.getUserId();
        redisTemplate.opsForValue().set(soulScoreKey,userInfo.getCharacterId().toString());

        return ResponseEntity.ok(userInfo.getCharacterId().toString());

    }

    /**
     * 接口名称：测灵魂-查看结果（学生实战）
     */
    public ResponseEntity<Object> report(String id) {

        // 根据id查询性格数据
        Character character = characterApi.findById(Integer.parseInt(id));

        // 封装vo数据
        CharacterVo characterVo = new CharacterVo();
        characterVo.setConclusion(character.getPersonality());
        characterVo.setCover(character.getCover());

        // 封装纬度数据
        List<DimensionsVo> dimensions = new ArrayList<>();
        DimensionsVo dimensionsVo = new DimensionsVo();
        dimensionsVo.setKey("外向");
        dimensionsVo.setValue("50%");
        dimensions.add(dimensionsVo);

        DimensionsVo dimensionsVo1 = new DimensionsVo();
        dimensionsVo1.setKey("判断");
        dimensionsVo1.setValue("50%");
        dimensions.add(dimensionsVo1);

        DimensionsVo dimensionsVo2 = new DimensionsVo();
        dimensionsVo2.setKey("抽象");
        dimensionsVo2.setValue("50%");
        dimensions.add(dimensionsVo2);

        DimensionsVo dimensionsVo3 = new DimensionsVo();
        dimensionsVo3.setKey("理性");
        dimensionsVo3.setValue("50%");
        dimensions.add(dimensionsVo3);

        characterVo.setDimensions(dimensions);

        // 封装与你相似数据
        List<UserInfo> userInfoList = userInfoApi.findByCharacter(Integer.parseInt(id));
        List<SimilarYouVo> similarYouVoList = new ArrayList<>();

        for (UserInfo userInfo : userInfoList) {
            SimilarYouVo  similarYouVo = new SimilarYouVo();
            if (userInfo.getId()!=UserHolder.getUserId()) {
                similarYouVo.setId(userInfo.getId().intValue());
                similarYouVo.setAvatar(userInfo.getAvatar());
                similarYouVoList.add(similarYouVo);
            }
        }
        characterVo.setSimilarYou(similarYouVoList);

        return ResponseEntity.ok(characterVo);
    }
}
